package org.client;

import java.io.File;
import java.util.Iterator;
import java.util.Vector;

import org.client.chat.ITalkClient;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.model.Friend;
import org.model.ViewUpdatable;

import com.cloudgarden.resource.SWTResourceManager;




public class ITalk extends org.eclipse.swt.widgets.Composite implements ViewUpdatable{
	private static Shell shell;
	private static Display display;
	private Text usernameTxt;
	private Label usernameLbl;
	private Text passwordTxt;
	private Label iTalk;
	private Button loginBtn;
	private Label passwordLbl;
	private PeerServerSocket mServerThread;
	private ChatServerConnector mChatServer;
	private byte[] key;
	private Vector<Friend> friendsVector;
	private Composite friendListComp;
	private int redrawUnit = 1;
	private String loginName;

	{
		SWTResourceManager.registerResourceUser(this);
	}

	public ITalk(Composite parent, int style) {
		super(parent, style);
		initGUI();
		Point size = getSize();
		shell.setLayout(new FillLayout());
		shell.setText("iTalk");
		File file = new File("src\\iTalk.png");
		Image image = new Image(display,file.getAbsolutePath());
		shell.setImage(image);
		shell.layout();
		
		if(size.x == 0 && size.y == 0) {
			pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		Rectangle screen = shell.getDisplay().getClientArea();
	    int screenHeigth = screen.height;
	    int screenWidth  = screen.width;
	    shell.setSize(300, (int) (screenHeigth *0.75));
	    shell.setLocation(screenWidth - 300, 0);
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		if(mChatServer != null)
			mChatServer.logOut();
		
	}
	
	/**
	* Initializes the GUI.
	*/
	private void initGUI() {
		try {
			this.setBackground(SWTResourceManager.getColor(145, 147, 238));
			FormLayout thisLayout = new FormLayout();
			this.setLayout(thisLayout);
			this.setSize(255, 433);
			{
				iTalk = new Label(this, SWT.NONE);
				FormData iTalkLData = new FormData();
				iTalkLData.width = 100;
				iTalkLData.height = 49;
				iTalkLData.left =  new FormAttachment(0, 1000, 82);
				iTalkLData.top =  new FormAttachment(0, 1000, 65);
				iTalk.setLayoutData(iTalkLData);
				iTalk.setText("iTalk");
				iTalk.setBackground(SWTResourceManager.getColor(145, 147, 238));
				iTalk.setForeground(SWTResourceManager.getColor(0, 0, 255));
				iTalk.setFont(SWTResourceManager.getFont("Monotype Corsiva", 36, 3, false, false));
			}
			{
				loginBtn = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData loginBtnLData = new FormData();
				loginBtnLData.width = 127;
				loginBtnLData.height = 23;
				loginBtnLData.left =  new FormAttachment(0, 1000, 68);
				loginBtnLData.top =  new FormAttachment(0, 1000, 273);
				loginBtn.setLayoutData(loginBtnLData);
				loginBtn.setText("Let Me In");
				loginBtn.setBackground(SWTResourceManager.getColor(0, 0, 255));
				loginBtn.setForeground(SWTResourceManager.getColor(0, 255, 0));
				loginBtn.setGrayed(true);
				loginBtn.addMouseListener(new MouseAdapter() {
					public void mouseUp(MouseEvent evt) {
						loginBtnMouseUp(evt);
						
					}
				});
			}
			{
				FormData passwordTxtLData = new FormData();
				passwordTxtLData.width = 89;
				passwordTxtLData.height = 15;
				passwordTxtLData.left =  new FormAttachment(0, 1000, 133);
				passwordTxtLData.top =  new FormAttachment(0, 1000, 214);
				passwordTxt = new Text(this, SWT.BORDER | SWT.PASSWORD);
				passwordTxt.setLayoutData(passwordTxtLData);
			}
			{
				passwordLbl = new Label(this, SWT.NONE);
				FormData passwordLblLData = new FormData();
				passwordLblLData.width = 60;
				passwordLblLData.height = 20;
				passwordLblLData.left =  new FormAttachment(0, 1000, 56);
				passwordLblLData.top =  new FormAttachment(0, 1000, 216);
				passwordLbl.setLayoutData(passwordLblLData);
				passwordLbl.setText("password");
				passwordLbl.setBackground(SWTResourceManager.getColor(145, 147, 238));
				passwordLbl.setForeground(SWTResourceManager.getColor(0, 0, 255));
				passwordLbl.setFont(SWTResourceManager.getFont("Tahoma", 10, 0, false, false));
			}
			{
				usernameLbl = new Label(this, SWT.NONE);
				FormData usernameLblLData = new FormData();
				usernameLblLData.width = 60;			
				usernameLblLData.height = 18;
				usernameLblLData.left =  new FormAttachment(0, 1000, 56);
				usernameLblLData.top =  new FormAttachment(0, 1000, 178);
				usernameLbl.setLayoutData(usernameLblLData);
				usernameLbl.setText("username");
				usernameLbl.setBackground(SWTResourceManager.getColor(145, 147, 238));
				usernameLbl.setForeground(SWTResourceManager.getColor(0, 0, 255));
				usernameLbl.setFont(SWTResourceManager.getFont("Tahoma", 10, 0, false, false));
			}
			{
				FormData usernameTxtLData = new FormData();
				usernameTxtLData.width = 88;
				usernameTxtLData.height = 15;
				usernameTxtLData.left =  new FormAttachment(0, 1000, 134);
				usernameTxtLData.top =  new FormAttachment(0, 1000, 176);
				usernameTxt = new Text(this, SWT.BORDER);
				usernameTxt.setLayoutData(usernameTxtLData);
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Auto-generated main method to display this 
	* org.eclipse.swt.widgets.Composite inside a new Shell.
	*/
	public static void main(String[] args) {
		display = Display.getDefault();
		shell = new Shell(display);
		new ITalk(shell, SWT.NULL);
	}
	
	
	
	private void loginBtnMouseUp(MouseEvent evt) {

		mServerThread = new PeerServerSocket();
		loginName = usernameTxt.getText();
		String password = passwordTxt.getText();
		
		int openPort = mServerThread.connect(loginName);
		mChatServer = new ChatServerConnector(loginName,password,openPort,(ViewUpdatable)ITalk.this);
		if(mChatServer.connect())
		{
			mChatServer.start();
			this.dispose();
			shell.setLayout(new FillLayout());

	        final ScrolledComposite sc = new ScrolledComposite(shell,SWT.V_SCROLL);
	        sc.setExpandHorizontal(true);
	        sc.setExpandVertical(true);
	        sc.getVerticalBar().setIncrement(5);

	        friendListComp = new Composite(sc, SWT.NONE);
	        friendListComp.setBackground(SWTResourceManager.getColor(255, 255, 255));
	        RowData data = new RowData();
	        
	        friendListComp.setLayoutData(data);
	        RowLayout layout = new RowLayout(SWT.VERTICAL);
	        //layout.fill = true;
	        layout.center = true;
	        //layout.justify = true;
	        layout.pack = true;
	        friendListComp.setLayout(layout);
	        showFriends();
	        
	        sc.addControlListener(new ControlAdapter() {
	            public void controlResized(ControlEvent e) {

	                Point p = friendListComp.computeSize(SWT.DEFAULT, SWT.DEFAULT);
	                sc.setMinSize(p.x, p.y + 10);
	                friendListComp.layout();
	            }
	        });
	        sc.setContent(friendListComp);        
	        shell.redraw();
	        shell.setSize(shell.getSize().x, shell.getSize().y+1);
		}
		else
		{
			MessageBox messageBox = new MessageBox(shell, SWT.OK);
			messageBox.setMessage("Invalid User,Plz validate your username and password");
			messageBox.open();
		}
	}
	private void showFriends() {
		if(friendsVector == null)
			return;
		Iterator<Friend> iter = friendsVector.iterator();
		for( Control control: friendListComp.getChildren() ) {
		    control.dispose();
		}
		int index = 0;
        while(iter.hasNext()){
        	CLabel friendLabel = new CLabel(friendListComp, SWT.SHADOW_OUT | SWT.LEFT | SWT.EMBEDDED | SWT.BORDER);
			RowData cLabel1LData = new RowData();
			cLabel1LData.width = shell.getSize().x;
			cLabel1LData.height = 52;
			
			friendLabel.setLayoutData(cLabel1LData);
			friendLabel.setText(iter.next().getName());
			friendLabel.setBackground(SWTResourceManager.getColor(145, 147, 238));
			friendLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
			friendLabel.setFont(SWTResourceManager.getFont("Tahoma", 10, 0, false, false));
			ClickHandler mouseHandler = new ClickHandler();
			mouseHandler.setIndex(index);
			friendLabel.addMouseListener(mouseHandler);
			index++;
			File file = new File("src\\org\\test\\chat.png");
			Image image = new Image(display,file.getAbsolutePath());
			friendLabel.setImage(image);			
			shell.setSize(shell.getSize().x, shell.getSize().y + redrawUnit);
			redrawUnit *= -1;
        }
    }

	@Override
	public void setPrivateKey(byte[] key) {
		this.key = key;
		mServerThread.setKey(key);
		mServerThread.start();
	}

	@Override
	public void updateView(Vector<Friend> friendsVector) {
		System.out.println("Friend Size"+friendsVector.size());
		this.friendsVector = friendsVector;
		if(friendListComp != null)
		{
			//if(!display.isDisposed()){
	            display.asyncExec (new Runnable ()
	            {
	               public void run () {
	                  //aGUI.doSomeGUIModifications();
	            	   System.out.println("i am here");
	            	   	ITalk.this.dispose();
	       				showFriends();
	               }
	            });
			//}
		}
	}
	
	private class ClickHandler extends MouseAdapter
	{

		private int index;
		public int getIndex() {
			return index;
		}
		public void setIndex(int index) {
			this.index = index;
		}
		@Override
		public void mouseDoubleClick(MouseEvent e) {
			super.mouseDoubleClick(e);
			System.out.println(index+" is clicked");
			Friend friend = friendsVector.get(index);
			new ITalkClient(friend,loginName,key);
		}
		
	}
}
